using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using WPFTemplateLib.CustomKeyboard;

namespace WPFTemplateLib.Attached
{
	/// <summary>
	/// Label 附加属性帮助类
	/// </summary>
	public class LabelAttached : DependencyObject
	{
		#region [附加属性] 键盘窗口类型
		public static Type GetKeyboardWindowType(DependencyObject obj)
		{
			return (Type)obj.GetValue(KeyboardWindowTypeProperty);
		}
		/// <summary>
		/// 键盘窗口类型
		/// </summary>
		public static void SetKeyboardWindowType(DependencyObject obj, Type value)
		{
			obj.SetValue(KeyboardWindowTypeProperty, value);
		}
		/// <summary>
		/// [附加属性] 键盘窗口类型
		/// </summary>
		public static readonly DependencyProperty KeyboardWindowTypeProperty =
			DependencyProperty.RegisterAttached("KeyboardWindowType", typeof(Type), typeof(LabelAttached), new PropertyMetadata(typeof(NumberKeyboard)));
		#endregion

		#region [附加属性] 是否使用自定义键盘

		public static bool GetIsUseCustomKeyboard(DependencyObject obj)
		{
			return (bool)obj.GetValue(IsUseCustomKeyboardProperty);
		}
		/// <summary>
		/// 是否使用自定义键盘
		/// </summary>
		public static void SetIsUseCustomKeyboard(DependencyObject obj, bool value)
		{
			obj.SetValue(IsUseCustomKeyboardProperty, value);
		}
		/// <summary>
		/// 是否使用自定义键盘
		/// </summary>
		public static readonly DependencyProperty IsUseCustomKeyboardProperty =
			DependencyProperty.RegisterAttached("IsUseCustomKeyboard", typeof(bool), typeof(LabelAttached), new PropertyMetadata(false, OnIsUseCustomKeyboardChanged));

		private static void OnIsUseCustomKeyboardChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var target = d as Label;
			if(target == null)
				return;

			if((bool)e.NewValue)
			{
				target.PreviewMouseLeftButtonDown += UseCustomKeyboard_PreviewMouseLeftButtonDown;
			}
			else
			{
				target.PreviewMouseLeftButtonDown -= UseCustomKeyboard_PreviewMouseLeftButtonDown;
			}
		}

		private static void UseCustomKeyboard_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			var label = sender as Label;
			if(label == null)
				return;

			string originValue = label.Content + "";
			Type keyboardWindowType = GetKeyboardWindowType(label);
			CustomKeyboardHelper.ShowCustomKeyboard(keyboardWindowType, originValue, newValue =>
			{
				label.Content = newValue;
			});
		}

		#endregion
	}
}
